import { Message, Tag } from '@arco-design/web-react';
import { useEffect, useState } from 'react';
import DetailModal from '../../../components/detailModal';
import LoadingMask from '../../../components/loadingMask';
import { flowKTOG } from '../../../utils/utils';
import { CardPackDetail,CardPayDetail,PayCouponCardUser } from '../packInfo/types';
import { apiGetProductCore } from '../../../api';
import { copyToClipboard } from '../../../utils/utils';
interface Props {
  cardId: string;
  onCancel: () => void;
}

/**
 * 资费展示项
 * hide 在客户端隐藏 需要带删除线
 */
interface CardPackShowItem {
  label: string;
  hide: boolean;
}
export default function CardPackInfoDialog({ cardId, onCancel }: Props) {
  // 套餐详情Popover展开后的展示数据
  const [cardProductCoreVo, setCardProductCoreVo] = useState<any>();
  useEffect(() => {
    loadCardProductCoreVo();
  }, []); // eslint-disable-line

  async function loadCardProductCoreVo() {
    if (!!cardProductCoreVo) return;
    LoadingMask.show('正在查询中...');
    try {
      let res = await apiGetProductCore(cardId);
      let data = res.data;
      if (data.code === 200) {
        setCardProductCoreVo(data.data);
      } else {
        Message.warning(data.msg ?? '查询失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '查询失败');
    } finally {
      LoadingMask.hide();
    }
  }
  // 根据套餐月份返回类型名
  function getPackTypeStr(t: number) {
    if (t < 3) {
      return '月包';
    } else if (t < 6) {
      return '季包';
    } else if (t < 12) {
      return '半年包';
    } else if (t < 24) {
      return '年包';
    } else {
      return '两年包';
    }
  }

  /** 隐藏的套餐ID */
  let concealPackDetailIds: (string | number)[] = cardProductCoreVo?.concealPackDetailIds ?? [];

  // 对应产品的套餐包列表
  let cardpackList: CardPackDetail[] = cardProductCoreVo?.cardPackDetails ?? [];
  // 基础包列表
  let baseMap: { [x: number]: CardPackShowItem[] } = {};
  let baseCopyData: { [x: number]: string } = {};
  // 加油包列表
  let fullMap: CardPackShowItem[] = [];
  let fullCopyData: string = '';
  // 日包列表
  let dayMap: CardPackShowItem[] = [];
  let dayCopyData: string = '';

  cardpackList.forEach((i) => {
    let hide = concealPackDetailIds.includes(i.id!);
    if (i.packageType === 'fuelpack') {
      let label = i.salePrice + '元 / ' + flowKTOG(i.totalFlow) + 'G';
      fullMap.push({ label, hide });
      if (!hide) {
        fullCopyData += label + '\n';
      }
    } else if (i.flowCalcTimeType === 'day') {
      let label = i.salePrice + '元 /' + flowKTOG(i.totalFlow) + 'G';
      dayMap.push({ label, hide });
      if (!hide) {
        dayCopyData += label + '\n';
      }
    } else {
      if (!baseMap[i.monthNum!]) {
        baseMap[i.monthNum!] = [];
        baseCopyData[i.monthNum!] = '';
      }
      let label = i.salePrice + '元/' + flowKTOG(i.totalFlow) + 'G';
      if (!hide) {
        baseCopyData[i.monthNum!] += label + '\n';
      }
      baseMap[i.monthNum!].push({ label, hide });
    }
  });
  // 充值包
  let cardPayList: CardPayDetail[] = cardProductCoreVo?.cardPayDetails ?? [];
  // 首充列表
  let first: string[] = [];
  // 续充列表
  let renewal: string[] = [];
  // 直充列表
  let direct: string[] = [];
  cardPayList.forEach((i) => {
    if (i.payType === 'first') {
      first.push(`充${i.payAmount!}得${i.amount}`);
    } else if (i.payType === 'renewal') {
      renewal.push(`充${i.payAmount!}得${i.amount}`);
    } else if (i.payType === 'direct') {
      direct.push(`充${i.payAmount!}得${i.amount}`);
    }
  });

  function handleCopy(type: 'packData' | 'chargeData') {
    if (type === 'packData') {
      let str = '';
      Object.keys(baseMap).forEach((k) => {
        str += `${getPackTypeStr(parseInt(k))}：\n` + baseCopyData[parseInt(k)] + '\n';
      });
      copyToClipboard(str + '日包：\n' + dayCopyData + '加油包：\n' + fullCopyData);
    } else {
      copyToClipboard(couponCopyData);
    }
  }

  let cardCouponList: PayCouponCardUser[] = cardProductCoreVo?.cardPayDetailCouponList ?? [];
  let couponCopyData: string = '';
  cardCouponList.forEach((i) => {
    couponCopyData += `${i.payDetailName} 送${i.couponName!} X${i.couponNum}张\n`;
  });
  return (
    <DetailModal
      show
      className="bw-80"
      title="资费套餐详情"
      onCancel={onCancel}
      onConfirm={onCancel}
      cancelBtnShow={false}
      confirmText="关闭"
    >
      <div className="bw-100 overflow-y h-400">
        {JSON.stringify(baseMap) !== '{}' && (
          <div className="d-flex-r ai-center">
            <div className="w-8 h-24 border-radius-8 bg-arcoblue-color"></div>
            <div className="ml-10 font-16 font-widget-600">套餐包</div>
            <Tag color="green" className="ml-20 cursor-pointer" onClick={() =>{
               handleCopy('packData')
            }}>
              复制
            </Tag>
          </div>
        )}
        <div className="bg-gray-color mt-10 border-radius-8 p-10">
          {JSON.stringify(baseMap) !== '{}' &&
            Object.keys(baseMap)
              .sort()
              .map((k: any) => (
                <div className="d-flex-r mb-5 font-12" key={k}>
                  <div className="text-primary-color font-widget-600 w-50 text-just">{getPackTypeStr(parseInt(k))}</div>
                  <div className="pl-5 pr-5">:</div>
                  <div className="flex-1">
                    {baseMap[k].map((i, idx) => (
                      <>
                        <span key={i.label + idx} className={`text-second-color ${i.hide ? 'text-deletelline' : ''}`}>
                          {i.label}
                        </span>
                        {baseMap[k].length === idx + 1 ? '' : '，'}
                      </>
                    ))}
                  </div>
                </div>
              ))}
          {dayMap.length > 0 && (
            <div className="d-flex-r mb-5 font-12" key="ribao">
              <div className="text-primary-color font-widget-600 w-50 text-just">日包</div>
              <div className="pl-5 pr-5">:</div>
              <div className="flex-1">
                {dayMap.map((i, idx) => (
                  <>
                    <span key={i.label + idx} className={`text-second-color ${i.hide ? 'text-deletelline' : ''}`}>
                      {i.label}
                    </span>
                    {dayMap.length === idx + 1 ? '' : '，'}
                  </>
                ))}
              </div>
            </div>
          )}
          {fullMap.length > 0 && (
            <div className="d-flex-r mb-5 font-12" key="jiayoubao">
              <div className="text-primary-color font-widget-600 w-50 text-just">加油包</div>
              <div className="pl-5 pr-5">:</div>
              <div className="flex-1">
                {fullMap.map((i, idx) => (
                  <>
                    <span key={i.label + idx} className={`text-second-color ${i.hide ? 'text-deletelline' : ''}`}>
                      {i.label}
                    </span>
                    {fullMap.length === idx + 1 ? '' : '，'}
                  </>
                ))}
              </div>
            </div>
          )}
        </div>
        <div className="d-flex-r ai-center mt-20">
          <div className="w-8 h-24 border-radius-8 bg-arcoblue-color"></div>
          <div className="ml-10 font-16 font-widget-600">充值类型</div>
        </div>
        <div className="bg-gray-color mt-10 border-radius-8 p-10">
          <div className="d-flex-r mb-5 font-12">
            <div className="text-primary-color font-widget-600 w-50 text-just">首充</div>
            <div className="pl-5 pr-5">:</div>
            <div className="flex-1">
              {!first.length && <span className="text-second-color">无</span>}
              {first.map((i, idx) => (
                <span key={i} className="text-second-color">
                  {i}
                  {first.length === idx + 1 ? '' : '，'}
                </span>
              ))}
            </div>
          </div>
          <div className="d-flex-r mb-5 font-12">
            <div className="text-primary-color font-widget-600 w-50 text-just">续充</div>
            <div className="pl-5 pr-5">:</div>
            <div className="flex-1">
              {!renewal.length && <span className="text-second-color">无</span>}
              {renewal.map((i, idx) => (
                <span key={i} className="text-second-color">
                  {i}
                  {renewal.length === idx + 1 ? '' : '，'}
                </span>
              ))}
            </div>
          </div>
          <div className="d-flex-r mb-5 font-12">
            <div className="text-primary-color font-widget-600 w-50 text-just">直充</div>
            <div className="pl-5 pr-5">:</div>
            <div className="flex-1">
              {!direct.length && <span className="text-second-color">无</span>}
              {direct.map((i, idx) => (
                <span key={i} className="text-second-color">
                  {i}
                  {direct.length === idx + 1 ? '' : '，'}
                </span>
              ))}
            </div>
          </div>
        </div>
        <div className="d-flex-r ai-center mt-20">
          <div className="w-8 h-24 border-radius-8 bg-arcoblue-color"></div>
          <div className="ml-10 font-16 font-widget-600">活动</div>
          <Tag color="green" className="ml-20 cursor-pointer" onClick={() => {
            handleCopy('chargeData')
          }}>
            复制
          </Tag>
        </div>
        <div className="bg-gray-color mt-10 border-radius-8 p-10 text-second-color">
          {cardCouponList.length <= 0 ? (
            <div className="font-12">无</div>
          ) : (
            cardCouponList.map((i) => (
              <div className="mb-5 font-12" key={i.id}>
                <span className="text-primary-color font-widget-600">{i.payDetailName}</span>
                <span className="pl-5 pr-5 text-second-color">送</span>
                <span className="text-gold-color">{i.couponName}</span>
                <span className="pl-5 text-error-color">{i.couponNum}张</span>
              </div>
            ))
          )}
        </div>
        <div className="d-flex-r ai-center mt-20">
          <div className="w-8 h-24 border-radius-8 bg-arcoblue-color"></div>
          <div className="ml-10 font-16 font-widget-600">资费介绍</div>
        </div>
        <div className="bg-gray-color mt-10 border-radius-8 p-10 text-second-color font-12">
          {cardProductCoreVo?.remark || '无'}
        </div>
      </div>
    </DetailModal>
  );
}
